package wikitools.servlet;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class FeedProxy
 */
public class FeedProxy extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FeedProxy() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("A Get Requested!........");
		serveFeed(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("A Post Requested!........");
		serveFeed(request, response);
	}



	private void serveFeed(HttpServletRequest request,
			HttpServletResponse response) throws MalformedURLException,
			IOException {
		String feed = request.getParameter("feed");
		
		URL feedurl = null;
		if (feed == null || feed.equals("")) {
			feedurl = new URL("http://localhost:8080/Wikitools/GetArticleList");

		}else {
		    feedurl = new URL(feed);
		}
		
//		ServletUtil.useProxy();
		response.setContentType("text/xml");
		String ret = ServletUtil.content(feedurl);
		ret = ret.replaceAll("<content:encoded>", "<content>");
		ret = ret.replaceAll("</content:encoded>", "</content>");
		ret = ret.replaceAll("<dc:creator>", "<author>");
		ret = ret.replaceAll("</dc:creator>", "</author>");
		ServletUtil.write(ret, response);

		System.out.println("Serving the feed...");

	}

}
